package org.jeecg.modules.client;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Component
public class HttpClient {

    private static final Logger log_error = LoggerFactory.getLogger("netty-error");

    public static Result<?> doClassPost(String url, Object myClass) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String resResult = "";
        try {
            // 创建httpClient实例
            httpClient = HttpClientBuilder.create().build();
            // 创建远程url连接对象
            HttpPost postUrl = new HttpPost(url);
            // 设置传入参数及格式
            String jsonSting = JSON.toJSONString(myClass);
            StringEntity requestEntity = new StringEntity(jsonSting, "UTF-8");
            postUrl.setEntity(requestEntity);
            postUrl.setHeader("Content-Type", "application/json;charset=utf-8");
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(postUrl);
            // 从响应对象中获取响应内容
            HttpEntity responseEntity = httpResponse.getEntity();
            resResult = EntityUtils.toString(responseEntity);
            return Result.OK(resResult);
        } catch (ClientProtocolException e) {
            log_error.error("http下发请求异常：{}",  e);
            return Result.error(resResult);
        } catch (Exception e) {
            log_error.error("http下发请求异常：{}",  e);
            return Result.error(resResult);
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
